package com.hzgj.bcl.soa.command;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * Created by Administrator on 2016/8/9.
 */
public class CommandsInitializer {

    public static final String REG_COMMAND = "reg";
    public static final String CONNECTIONS_COMMAND = "connections";
    public static final String BIZCOUNT_COMMAND = "bizCount";
    public static final String INVOKE_COMMAND = "invoke";
    public static final String RELATION_COMMAND = "relation";
    public static final String CLIENT_COMMAND = "client";
    public static final String UPORDOWNSERVICE_COMMAND = "upOrDownService";

    static Map<String, SoaCommand> commands = Maps.newHashMap();

    public static void load() {
        ServiceLoader<SoaCommand> serviceLoader = ServiceLoader.load(SoaCommand.class);
        List<SoaCommand> after = Lists.newArrayList(serviceLoader.iterator());
        after.stream().sorted((o1, o2) -> {
            if (o1.getSequence() > o2.getSequence()) {
                return -1;
            } else if (o1.getSequence() < o2.getSequence()) {
                return 1;
            } else {
                return 0;
            }
        }).forEach(command -> {
            command.start();
            commands.put(command.getName(), command);
        });
    }

    public static <T extends SoaCommand> T getCommand(String name) {
        return (T) commands.get(name);
    }

    public abstract static class InternalCommand extends BaseCommand {
        public abstract Object invoke0(CommandOptions commandOptions);
    }
}

abstract class BaseCommand implements SoaCommand {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void start() {
    }
}



